<!-- src/views/dept/DeptDetail.vue -->
<template>
  <div class="dept-detail-container">
    <!-- 部门基本信息 -->
    <el-card class="dept-info-card">
      <template #header>
        <div class="card-header">
          <span>部门基本信息</span>
          <div>
            <el-button type="primary" @click="handleEdit">编辑</el-button>
            <el-button type="success" @click="handleCreate">新增子部门</el-button>
            <el-button type="danger" @click="handleDelete">删除</el-button>
          </div>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="部门编号">{{ deptInfo.id }}</el-descriptions-item>
        <el-descriptions-item label="部门名称">{{ deptInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="父部门编号">{{ deptInfo.parentId }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(deptInfo.createdTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(deptInfo.updatedTime) }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ deptInfo.description || '无描述' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 员工列表 -->
    <el-card class="employee-list-card">
      <template #header>
        <div class="card-header">
          <span>部门员工列表</span>
        </div>
      </template>

      <el-table :data="employeeList" style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="100"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="realName" label="真实姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEditEmployee(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleRemoveEmployee(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 员工分页 -->
      <el-pagination
        :total="employeePagination.total"
        :page-size="employeePagination.pageSize"
        :current-page="employeePagination.currentPage"
        @current-change="handleEmployeePageChange"
        layout="prev, pager, next, jumper, ->, total"
        background
        class="employee-pagination"
      />
    </el-card>

    <!-- 部门编辑对话框 -->
    <DeptEdit ref="deptEditRef" />

    <!-- 部门创建对话框 -->
    <DeptCreate ref="deptCreateRef" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDeptStore } from '@/stores/deptStore.js'
import DeptEdit from '@/views/system/DeptEdit.vue' // 引入部门编辑组件
import DeptCreate from '@/views/dept/DeptCreate.vue' // 引入部门创建组件

const route = useRoute()
const router = useRouter()
const deptStore = useDeptStore()

// 部门信息
const deptInfo = ref({})

// 员工列表
const employeeList = ref([])

// 部门编辑组件引用
const deptEditRef = ref(null)
// 部门创建组件引用
const deptCreateRef = ref(null)

// 员工分页信息
const employeePagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 获取部门详情
const fetchDeptDetail = async () => {
  try {
    const deptId = deptStore.deptDetail.id
    // 调用真实的API获取部门详情
    console.log('Fetching department detail for ID:', deptId)
    const deptDetail = await deptStore.getDeptDetail(deptId);
    console.log('Department detail response:', deptDetail)

    if (deptDetail) {
      deptInfo.value = deptDetail;
    } else {
      ElMessage.error('未获取到部门详情')
      return
    }

    // 获取部门员工列表
    const userData = await deptStore.getDeptUsers(deptId);
    console.log('User data response:', userData)

    if (userData) {
      employeeList.value = userData.records || [];
      employeePagination.total = userData.total || 0;
      employeePagination.pageSize = userData.pageSize || 10;
      employeePagination.currentPage = userData.pageNum || 1;
    }
  } catch (error) {
    console.error('获取部门详情失败:', error)
    ElMessage.error('获取部门详情失败: ' + (error.message || error))
  }
}

onMounted(() => {
    fetchDeptDetail()
})

// 编辑部门
const handleEdit = () => {
  // 调用 DeptEdit 组件的 show 方法，传入当前部门信息
  deptEditRef.value.show({
    id: deptInfo.value.id,
    name: deptInfo.value.name,
    parentId: deptInfo.value.parentId,
    sort: deptInfo.value.sort,
    description: deptInfo.value.description
  })
}

// 新增：创建子部门
const handleCreate = () => {
  // 调用 DeptCreate 组件的 show 方法
  deptCreateRef.value.show()
}

// 删除部门
const handleDelete = async () => {
  ElMessageBox.confirm(
    `确定要删除部门 "${deptInfo.value.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const result = await deptStore.deleteDept(deptInfo.value.id);
      if (result && result.code === 200) {
        ElMessage.success('删除成功');
        router.back();
      } else {
        ElMessage.error(result?.message || '删除失败');
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.message || error));
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 编辑员工
const handleEditEmployee = (employee) => {
  ElMessage.info(`编辑员工: ${employee.realName}`)
}

// 移除员工
const handleRemoveEmployee = (employee) => {
  ElMessageBox.confirm(
    `确定要将员工 "${employee.realName}" 从该部门移除吗？`,
    '确认移除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    ElMessage.success('移除成功')
    // 这里应该调用移除员工接口
  }).catch(() => {
    ElMessage.info('已取消移除')
  })
}

// 员工分页变化
const handleEmployeePageChange = async (page) => {
  employeePagination.currentPage = page
  // 重新加载员工数据
  try {
    const userData = await deptStore.getDeptUsers(deptInfo.value.id, {
      pageNum: page,
      pageSize: employeePagination.pageSize
    });
    if (userData) {
      employeeList.value = userData.records || [];
    }
  } catch (error) {
    ElMessage.error('获取员工列表失败: ' + (error.message || error));
  }
}
</script>

<style scoped>
.dept-detail-container {
  padding: 20px;
}

.dept-info-card,
.employee-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.employee-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-descriptions__cell) {
  min-width: 150px;
}
</style>
